# -*- coding:utf-8 -*-

"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: 2023/5/29:18:01
@product: PyCharm
=============================
"""
import os
import sys
import serial
from PyQt5.QtWidgets import QDialog, QApplication

import ui_dialog


def linuxSudoCmd(cmd):
    password = os.environ.get("platform4_linuxPassword")
    command = cmd
    try:
        os.system('echo %s | sudo -S %s' % (password, command))
    except Exception as e:
        print(e)


# 计算和校验值并转字符串
def calCheckSum(data):
    try:
        if max(data) > 255:
            return []
        s = sum(data)
        res = data
        res.append(int(s / 250 % 250))
        res.append(int(s % 250))
        return res
    except Exception as e:
        print(e)
        print("serial calCheckSumAndTurnString failed...")
        return []


def sendDebugCmd():
    ser = serial.Serial('/dev/ttyS3', 115200)
    rawPackList = [0xfe, 0x06, 0x15, 1]
    ser.write(calCheckSum(rawPackList))


class UpdateSW(QDialog, ui_dialog.Ui_Dialog):

    def __init__(self, mode='master', parent=None):
        super(UpdateSW, self).__init__(parent)
        self.setupUi(self)
        if 'dev' in mode or 'zzz':
            self.mode = 'dev'
        if 'master' in mode:
            self.mode = 'master'

        infoStr = self.infoLabel.text()
        if self.mode == 'dev':
            infoStr = infoStr.replace('<0>', '<develop>')
            infoStr = infoStr.replace('<1>', '<测试>')
        else:
            infoStr = infoStr.replace('<0>', '<master>')
            infoStr = infoStr.replace('<1>', '<稳定>')
        self.infoLabel.setText(infoStr)
        self.setGeometry(int((800 - self.width()) / 2), int((480 - self.height()) / 2), self.width(), self.height())

        self.backBtn.clicked.connect(self.reject)
        self.upgradeBtn.clicked.connect(self.update)

    def update(self):
        # 发送调试模式指令，防止重启
        # 5a6f之后区分国内国外，国内继续沿用dev，国外使用zzz分支
        filename = '/home/feibot/.feibotUserConfig.ini'
        language = os.popen('sed -n {}p {}'.format(2, filename)).read()
        sendDebugCmd()
        pathName = os.path.dirname(os.path.realpath(__file__))
        if self.mode == 'dev':
            if 'chinese' not in language:
                cmd = 'bash ' + os.path.join(pathName, 'update_cmd_sw_zzz.sh')
            else:
                cmd = 'sh ' + os.path.join(pathName, 'update_cmd_sw_dev.sh')
        else:
            cmd = 'sh ' + os.path.join(pathName, 'update_cmd_sw_master.sh')
        linuxSudoCmd(cmd)
        sys.exit(1)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    if len(sys.argv) >= 2:
        form = UpdateSW(sys.argv[1])
    else:
        form = UpdateSW('master')
    form.show()
    app.exec_()
    sys.exit(0)
